from langchain_core.tools import tool
import pandas as pd
import json
from collections import defaultdict, Counter
from datetime import datetime
import numpy as np
import sys
import os

# 添加项目路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))

from ai.services.amap_service import amap_service

@tool
def area_recommendation_tool(query: str) -> str:
    """
    基于相似司机的成功经验推荐最佳调度区域。
    
    Args:
        query: JSON字符串，格式：{"input_file": "driver_data.csv", "similar_drivers": [...], "time_category": "morning_peak", "top_areas": 5}
    
    Returns:
        推荐的热点区域列表
    """
    try:
        params = json.loads(query)
        input_file = params.get('input_file', 'driver_order_data.csv')
        similar_drivers = params.get('similar_drivers', [])
        time_category = params.get('time_category', 'morning_peak')
        top_areas = params.get('top_areas', 5)

        # 加载CSV数据
        file_path = f'ai_data/{input_file}'
        df = pd.read_csv(file_path)

        if not similar_drivers:
            return "没有提供相似司机数据"

        # 提取相似司机ID列表
        similar_driver_ids = [driver['driver_id'] for driver in similar_drivers]

        # 筛选相似司机在指定时段的数据
        filtered_data = df[
            (df['driver_id'].isin(similar_driver_ids)) &
            (df['time_category'] == time_category)
        ]

        if filtered_data.empty:
            return f"没有找到相似司机在 {time_category} 时段的数据"

        # 计算区域推荐分数
        area_recommendations = []
        area_stats = filtered_data.groupby('area_id').agg({
            'order_count': ['sum', 'mean', 'count'],
            'driver_id': 'nunique',
            'avg_amount': 'mean',
            'active_days': 'sum'
        }).round(2)

        area_stats.columns = ['total_orders', 'avg_orders_per_driver', 'driver_sessions', 'unique_drivers', 'avg_amount', 'total_active_days']

        # 计算各指标的最大值用于标准化
        max_total_orders = area_stats['total_orders'].max()
        max_avg_orders_per_driver = area_stats['avg_orders_per_driver'].max()
        max_unique_drivers = area_stats['unique_drivers'].max()
        max_avg_amount = area_stats['avg_amount'].max()
        max_driver_sessions = area_stats['driver_sessions'].max()

        for area_id in area_stats.index:
            stats = area_stats.loc[area_id]

            # 标准化各指标到0-1范围
            normalized_total_orders = float(stats['total_orders']) / max_total_orders if max_total_orders > 0 else 0
            normalized_avg_orders = float(stats['avg_orders_per_driver']) / max_avg_orders_per_driver if max_avg_orders_per_driver > 0 else 0
            normalized_unique_drivers = float(stats['unique_drivers']) / max_unique_drivers if max_unique_drivers > 0 else 0
            normalized_avg_amount = float(stats['avg_amount']) / max_avg_amount if max_avg_amount > 0 else 0
            normalized_driver_sessions = float(stats['driver_sessions']) / max_driver_sessions if max_driver_sessions > 0 else 0

            # 计算推荐分数（标准化到0-100范围）
            recommendation_score = (
                normalized_total_orders * 0.35 +  # 总订单量权重35%
                normalized_avg_orders * 0.25 +  # 平均表现权重25%
                normalized_unique_drivers * 0.20 +  # 司机多样性权重20%
                normalized_avg_amount * 0.15 +  # 平均收入权重15%
                normalized_driver_sessions * 0.05  # 活跃度权重5%
            ) * 100  # 转换为0-100分制

            # 解析区域坐标
            try:
                lng, lat = area_id.split('_')
                lng, lat = float(lng), float(lat)
            except:
                lng, lat = 0.0, 0.0

            # 获取地点名称
            location_name = amap_service.get_location_name(lng, lat)

            # 计算成功率
            driver_sessions = max(float(stats['driver_sessions']), 1.0)
            success_rate = min(float(stats['avg_orders_per_driver']) / driver_sessions, 1.0)

            area_recommendations.append({
                'area_id': area_id,
                'longitude': lng,
                'latitude': lat,
                'location_name': location_name,  # 添加地点名称
                'recommendation_score': round(float(recommendation_score), 2),
                'total_orders': int(stats['total_orders']),
                'avg_orders_per_driver': float(stats['avg_orders_per_driver']),
                'unique_drivers': int(stats['unique_drivers']),
                'avg_amount': float(stats['avg_amount']),
                'total_active_days': int(stats['total_active_days']),
                'success_rate': round(success_rate, 2)
            })

        # 按推荐分数排序
        area_recommendations.sort(key=lambda x: x['recommendation_score'], reverse=True)
        top_recommendations = area_recommendations[:top_areas]

        # 生成推荐理由
        recommendations_with_reasons = []
        for i, area in enumerate(top_recommendations):
            reason = _generate_recommendation_reason(area, i+1, time_category)
            area['recommendation_reason'] = reason
            recommendations_with_reasons.append(area)

        result = {
            'time_category': time_category,
            'analysis_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'similar_drivers_count': len(similar_driver_ids),
            'total_areas_analyzed': len(area_recommendations),
            'top_recommendations': recommendations_with_reasons,
            'analysis_summary': {
                'total_orders_analyzed': int(filtered_data['order_count'].sum()),
                'avg_orders_per_area': round(float(filtered_data['order_count'].mean()), 2),
                'total_revenue': round(float(filtered_data['order_count'].sum() * filtered_data['avg_amount'].mean()), 2)
            }
        }

        return f"区域推荐完成：{json.dumps(result, ensure_ascii=False, indent=2)}"

    except Exception as e:
        return f"区域推荐失败：{str(e)}"


def _generate_recommendation_reason(area, rank, time_category):
    """生成推荐理由"""
    reasons = []

    # 基于新的0-100分制评分
    if area['recommendation_score'] > 80:
        reasons.append("综合评分很高")
    elif area['recommendation_score'] > 60:
        reasons.append("综合评分良好")
    elif area['recommendation_score'] > 40:
        reasons.append("综合评分一般")

    if area['total_orders'] > 30:
        reasons.append("历史订单量充足")
    elif area['total_orders'] > 15:
        reasons.append("历史订单量适中")

    if area['success_rate'] > 0.8:
        reasons.append("司机成功率高")
    elif area['success_rate'] > 0.6:
        reasons.append("司机成功率良好")

    if area['unique_drivers'] > 8:
        reasons.append("多位相似司机验证")
    elif area['unique_drivers'] > 5:
        reasons.append("多位司机验证")

    if area['avg_amount'] > 50:
        reasons.append("平均收入较高")
    elif area['avg_amount'] > 30:
        reasons.append("平均收入适中")

    time_desc = {
        'morning_peak': '早高峰',
        'evening_peak': '晚高峰',
        'night_peak': '夜间高峰',
        'normal': '平时'
    }.get(time_category, time_category)

    base_reason = f"在{time_desc}时段排名第{rank}"
    if reasons:
        return f"{base_reason}，{', '.join(reasons)}"
    else:
        return base_reason

